package com.ruoyi.common.utils.glmApi;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class GlmUtils {

    public static GlmRes glmUtil(String content, String role) {
        String url = "https://open.bigmodel.cn/api/paas/v4/chat/completions";

        String authorization = "84ab304d489785cf97c650b34a5eadf5.FcqNIprV2Jy0oUwv";

        // 创建Message对象
        Message message = new Message();
        message.setContent(content);
        message.setRole(role);

        // 创建MyModel对象
        Body body = new Body(Collections.singletonList(message));

        // 转换为JSON字符串
        String jsonString = JSONUtil.toJsonStr(body);


        //调用GLM
        String result = HttpRequest

                .post(url)
                .header("Content-Type", "application/json")
                .header("Authorization", authorization)
                .body(jsonString)
                .execute()
                .body();

        JSONObject jsonObject = JSONUtil.parseObj(result);

        GlmRes glmRes = JSONUtil.toBean(result, GlmRes.class);

        String choicesStr = jsonObject.getStr("choices");
        if (choicesStr.startsWith("[") && choicesStr.endsWith("]")) {
            choicesStr = choicesStr.substring(1, choicesStr.length() - 1);
        }
        Choices choices = JSONUtil.toBean(choicesStr, Choices.class);

        String usageStr = jsonObject.getStr("usage");
        Usage usage = JSONUtil.toBean(usageStr, Usage.class);

        glmRes.setChoices(choices);
        glmRes.setUsage(usage);

        return glmRes;
    }
}
